package org.zebra.mybatis.plus.ext.redundancy;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.zebra.mybatis.plus.ext.redundancy.annotation.RedundancyField;
import org.zebra.mybatis.plus.ext.redundancy.util.BeanClassUtil;
import org.zebra.mybatis.plus.util.MyBatisPlusUtil;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 主要是为了提升性能
 *
 * @author zhanghongbin
 */
public final class RedundancyFieldInterceptorRegister {

    private RedundancyFieldInterceptorRegister() {}

    public static boolean register(List<TableInfo> tableInfos) {
        boolean hasRedundancyField = false;
        for (TableInfo tableInfo : tableInfos) {
            Class<?> entityClass = tableInfo.getEntityType();
            if (entityClass == null) continue;
            List<Field> allDeclaredFields = BeanClassUtil.getAllDeclaredFieldsExcludeStatic(entityClass);
            for (Field entityField : allDeclaredFields) {
                // 扫描所有的Entity中的RedundancyField注解
                RedundancyField redundancyField =
                        AnnotatedElementUtils.findMergedAnnotation(entityField, RedundancyField.class);
                if (redundancyField == null) continue;
                if (RedundancyFieldManager.addRedundancyField(entityClass, entityField, redundancyField)) {
                    hasRedundancyField = true;
                }
            }
        }
        // 动态增加 mybatis 拦截器主要是为了提升效率
        if (hasRedundancyField) {
            MyBatisPlusUtil.addInterceptor(new RedundancyFieldInterceptor());
        }
        return hasRedundancyField;
    }
}
